/*** 
 * @Date: 2020-07-10 09:33:27
 * @LastEditors: leehave
 * @LastEditTime: 2020-09-15 09:17:37
 */
import axios from 'axios'
import { Dialog, Toast } from 'vant'
import store from '@/store'
import qs from 'qs'
import { loadToken } from '@/utils/cache'
import { PORT } from '@/service/api'
import { HTTP_RESP_CODE } from '@/constant'

// console.log(process.env.VUE_APP_API_URL,'process.env.VUE_APP_API_URL')
const service = axios.create({
  // baseURL: 'http://cloud.henankejue.com/weixin', 
  baseURL: process.env.VUE_APP_API_URL, 
  timeout: 20000 // request timeout
})

const errorReport = error => {
  const { config, data } = error
  const { url } = config
  if (window.$sentry) {
    const errorInfo = {
      error: typeof error === 'string' ? new Error(error) : error,
      type: 'request',
      requestUrl: url,
      requestOptions: JSON.stringify(config)
    }
    if (data) {
      errorInfo.response = JSON.stringify(data)
    }

    window.$sentry.log && window.$sentry.log(errorInfo)
  }
}

const responseLog = response => {
  if (process.env.NODE_ENV === 'development') {
    const randomColor = `rgba(${Math.round(
      Math.random() * 255
    )},${Math.round(Math.random() * 255)},${Math.round(
      Math.random() * 255
    )})`
    console.log(
      '%c┍------------------------------------------------------------------┑',
      `color:${randomColor};`
    )
    console.log('| 请求地址：', response.config.url)
    console.log(
      '| 请求参数：',
      response.config.data ? qs.parse(response.config.data) : {}
    )
    console.log('| 返回数据：', response.data)
    console.log(
      '%c┕------------------------------------------------------------------┙',
      `color:${randomColor};`
    )
  }
}
let header = {
  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
  'X-Requested-With': 'XMLHttpRequest'
}
// request interceptor
service.interceptors.request.use(
  config => {
    if (config.url.includes(PORT.login) || config.url.includes(PORT.authInfo) || config.url.includes(PORT.appInfo)) {
      delete header.Authorization
    }else{
      config.headers['Authorization'] = `Bearer ${loadToken()}`
    }
    config.headers = config.headers ? config.headers : header
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    responseLog(response)
    const res = response.data
    if (res.status != HTTP_RESP_CODE.SUCCESS) {
      if(res.status == 204){
        return res
      }
      console.log(res,'未成功的status')
      // 错误提示
      
      // 警告提示
      if (res.status === HTTP_RESP_CODE.WARN) {
        Dialog.alert({
          title: '重要提醒',
          message: res.respMsg
        }).then(() => {})
      }
      // token 过期
      if (res.status === HTTP_RESP_CODE.ACCOUNT_RESET_TOKEN) {
        store.dispatch('user/fedLogOut')
        return
      }
      // errorReport(response)
      Toast.fail(res.message || '请求出错')
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    // errorReport(error)
    console.log('err' + error) // for debug
    Toast.fail(error.message || '请求出错')
    return Promise.reject(error)
  }
)

export default service
